{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "115cb4c2",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Pandas基本用法\n",
    "http://c.biancheng.net/pandas/series.html"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a0794482",
   "metadata": {},
   "source": [
    "## Pandas的特点\n",
    "1. 它提供了一个简单、高效、带有默认标签（也可以自定义标签）的 DataFrame 对象。\n",
    "2. 能够快速得从不同格式的文件中加载数据（比如 Excel、CSV 、SQL文件），然后将其转换为可处理的对象；\n",
    "3. 能够按数据的行、列标签进行分组，并对分组后的对象执行聚合和转换操作；\n",
    "4. 能够很方便地实现数据归一化操作和缺失值处理；\n",
    "5. 能够很方便地对 DataFrame 的数据列进行增加、修改或者删除的操作；\n",
    "6. 能够处理不同格式的数据集，比如矩阵数据、异构数据表、时间序列等；\n",
    "7. 提供了多种处理数据集的方式，比如构建子集、切片、过滤、分组以及重新排序等。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44eb43e4",
   "metadata": {},
   "source": [
    "## Pandas的Series（一维数据结构）与DataFrame（二维数据结构）\n",
    "- Series 结构，它是一种类似于一维数组的结构，由一组数据值（value）和一组标签组成，其中标签与数据值之间是一一对应的关系。\n",
    "\n",
    "- DataFrame 是一种表格型数据结构，它既有行标签，又有列标签。\n",
    "\n",
    "DataFrame的特点：\n",
    "1. DataFrame 是一种二维表格型数据的结构\n",
    "2. 既有行索引，也有列索引。\n",
    "3. 行索引是 index，列索引是 columns。\n",
    "4. 在创建该结构时，可以指定相应的索引值。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b7ace72",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Series对象\n",
    "## 创建Series对象\n",
    "### 创建一个空的Series对象"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2092d10f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Series([], dtype: float64)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/py_env/jupyter/lib/python3.6/site-packages/ipykernel_launcher.py:4: DeprecationWarning: The default dtype for empty Series will be 'object' instead of 'float64' in a future version. Specify a dtype explicitly to silence this warning.\n",
      "  after removing the cwd from sys.path.\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "#输出数据为空\n",
    "s = pd.Series()\n",
    "print(s)\n",
    "\n",
    "# pd.Series()的参数含义\n",
    "# data，输入的数据可以是列表，常量，ndarray数组\n",
    "# index，索引值。 默认为np.arrange(n)\n",
    "# dtype  数据类型， 默认自动判断\n",
    "# copy   对data进行拷贝， 默认为False"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e7bd548",
   "metadata": {},
   "source": [
    "### 用ndarrray创建一个Series对象（自定义索引标签）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e522f356",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "100    a\n",
      "200    b\n",
      "300    c\n",
      "400    d\n",
      "dtype: object\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "# 创建数据\n",
    "data = np.array(['a','b','c','d'])\n",
    "\n",
    "# 创建Series对象\n",
    "# 自定义索引标签label\n",
    "label = [100,200,300,400]\n",
    "\n",
    "s = pd.Series(data,index=label)\n",
    "\n",
    "\n",
    "print (s)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78aff781",
   "metadata": {},
   "source": [
    "### 用dict创建Series对象（自定义index时，没有的key会以NaN补充）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9b0e3214",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "b    1\n",
      "c    2\n",
      "dtype: int64\n",
      "b    1.0\n",
      "c    2.0\n",
      "a    0.0\n",
      "d    NaN\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "# 使用dict做data时，如果\n",
    "# 我们没有自定义index，则以key值作为索引\n",
    "data = {'a':0,'b':1,'c':2} \n",
    "s = pd.Series(data)\n",
    "print(s)\n",
    "# 当自定义index时，没有的key会以NaN补充\n",
    "s1 = pd.Series(data,index=['b','c','a','d'])\n",
    "print(s1)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "56099968",
   "metadata": {},
   "source": [
    "### 标量创建Series对象\n",
    "- 如果data是标量，则必须要自定义索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a179bb54",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    5\n",
      "dtype: int64\n",
      "1    5\n",
      "2    5\n",
      "3    5\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# 不给索引,只创建一个\n",
    "s1 = pd.Series(5)\n",
    "print(s1)\n",
    "# 给索引，创建n个，n对应索引数目\n",
    "s2 = pd.Series(5,index=['1','2','3'])\n",
    "print(s2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ceabb798",
   "metadata": {},
   "source": [
    "## 访问Series数据\n",
    "1. 位置下标访问，序号索引\n",
    "2. 标签下标访问，标签索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "2816f34d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Series:\n",
      "\n",
      "a    1\n",
      "b    2\n",
      "c    3\n",
      "d    4\n",
      "e    5\n",
      "dtype: int64\n",
      "index索引： 1\n",
      "label索引： 1\n",
      "切片结果:\n",
      "\n",
      "c    3\n",
      "d    4\n",
      "e    5\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])\n",
    "print('Series:\\n')\n",
    "print(s)\n",
    "print('index索引：',s[0])  #使用位置下标\n",
    "print('label索引：',s['a']) #使用标签下标\n",
    "# 切片的方式也行\n",
    "print('切片结果:\\n')\n",
    "print(s[-3:])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "016ca542",
   "metadata": {},
   "source": [
    "## Series对象的常用属性"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "a4b5931a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Series.axes  以两层嵌套的list类型返回索引索引的标签\n",
    "# Series.dtype 返回对象数据类型\n",
    "# Series.empty Series是否为空，返回bool值\n",
    "# Series.ndim  返回数据的维度\n",
    "# Series.size  返回数据的元素个数\n",
    "# Series.value 以ndarray的类型返回值\n",
    "# Series.index 以pandas的对象，返回索引取值范围\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ac1796f",
   "metadata": {},
   "source": [
    "## Series对象的常用方法\n",
    "### 查看数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "627eed9d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    1\n",
      "b    2\n",
      "dtype: int64\n",
      "c    3\n",
      "d    4\n",
      "e    5\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# head(n) 查看前n行数据,默认n为5\n",
    "print(s.head(2))\n",
    "# tail(n) 查看后n行数据，默认n为5\n",
    "print(s.tail(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c9d41f5f",
   "metadata": {},
   "source": [
    "### 检查Series中是否存在缺失值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "872a9f31",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "a    False\n",
       "b    False\n",
       "c    False\n",
       "d    False\n",
       "e    False\n",
       "dtype: bool"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# isnull() 判断元素，它是null值吗？\n",
    "s.isnull()\n",
    "# nonull() 是isnull()相反的"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75686364",
   "metadata": {
    "tags": []
   },
   "source": [
    "# DataFrame对象\n",
    "## DataFrame对象的特点\n",
    "\n",
    "DataFrame 就像一个excel中的sheet表\n",
    "1. DataFrame的每一行都可以看作一个Series对象\n",
    "2. index就是行标签，columns就是列标签\n",
    "3. DataFrame的每一列允许数据类型不同\n",
    "4. DataFrame允许增删改查\n",
    "5. DataFrame可以进行列与行的算术运算"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0277cf6d",
   "metadata": {},
   "source": [
    "## 创建DataFrame对象\n",
    "### 创建空DataFrame对象"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "07e65961",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Empty DataFrame\n",
      "Columns: []\n",
      "Index: []\n"
     ]
    }
   ],
   "source": [
    "df = pd.DataFrame()\n",
    "print(df)\n",
    "\n",
    "# pd.DataFrame(data,index,columns,dtype,copy)\n",
    "### DataFrame参数：\n",
    "## data 输入数据，可以是：\n",
    "   # 1.ndarray，series，list，dict\n",
    "   # 2.标量以及一个 DataFrame。\n",
    "## index 行标签\n",
    "## columns 列标签\n",
    "## dtype 每一列的数据类型\n",
    "## copy 是否copy"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f7c707a",
   "metadata": {},
   "source": [
    "#### 用list创建DateFrame对象"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "801a620f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   0  1  2  3  4\n",
      "0  1  2  3  4  5\n",
      "1  1  2  3  4  5\n"
     ]
    }
   ],
   "source": [
    "# 与np.ndarray创建不同的是，DataFrame最高为2维，\n",
    "#更多的嵌套会被当做一个整体元素\n",
    "data = [[1,2,3,4,5],[1,2,3,4,5]]\n",
    "df = pd.DataFrame(data)\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "762d8b6b",
   "metadata": {},
   "source": [
    "#### 用dict创建DataFrame对象（并为其添加行，列标签）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "9e8e83b2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       fk  wwx  Age   Name\n",
      "day1  NaN  NaN   28    Tom\n",
      "day2  NaN  NaN   34   Jack\n",
      "day3  NaN  NaN   29  Steve\n",
      "day4  NaN  NaN   42  Ricky\n",
      "day1    NaN\n",
      "day2    NaN\n",
      "day3    NaN\n",
      "day4    NaN\n",
      "Name: fk, dtype: object\n"
     ]
    }
   ],
   "source": [
    "# key作为列标签，value这列的元素\n",
    "data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}\n",
    "\n",
    "# 用index为其添加行标签\n",
    "# 在用columns自定义列标签时，\n",
    "  # 1.如果不包含dict中的某一个key，这个key会被忽略。\n",
    "  # 2.如果dict不存在这个key，会以NaN填充这一列\n",
    "df = pd.DataFrame(data,index=['day1','day2','day3','day4'],columns=['fk','wwx','Age','Name'])\n",
    "\n",
    "print(df)\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e7b9296a",
   "metadata": {},
   "source": [
    "## 列索引操作DataFrame\n",
    "### 使用列索引查找列（查）\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "id": "3a734b8b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    1.0\n",
      "b    2.0\n",
      "c    3.0\n",
      "d    NaN\n",
      "Name: one, dtype: float64\n"
     ]
    }
   ],
   "source": [
    "d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),\n",
    "   'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}\n",
    "df = pd.DataFrame(d)\n",
    "print(df ['one'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb977de3",
   "metadata": {},
   "source": [
    "### 增加DataFrame列数据（增）"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f93eba88",
   "metadata": {},
   "source": [
    "#### 使用列索引创建新的数据列（增）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "id": "d0fd3c49",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       fk  wwx  Age   Name  lxl\n",
      "day1  NaN  NaN   28    Tom  NaN\n",
      "day2  NaN  NaN   34   Jack  NaN\n",
      "day3  NaN  NaN   29  Steve  NaN\n",
      "day4  NaN  NaN   42  Ricky  NaN\n"
     ]
    }
   ],
   "source": [
    "# key作为列标签，value这列的元素\n",
    "data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}\n",
    "\n",
    "# 用index为其添加行标签\n",
    "# 在用columns自定义列标签时，\n",
    "  # 1.如果不包含dict中的某一个key，这个key会被忽略。\n",
    "  # 2.如果dict不存在这个key，会以NaN填充这一列\n",
    "df = pd.DataFrame(data,index=['day1','day2','day3','day4'],columns=['fk','wwx','Age','Name'])\n",
    "\n",
    "df['lxl'] = pd.Series([10,20,30])\n",
    "\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1adb379a",
   "metadata": {},
   "source": [
    "#### 用insert()函数为df插入新列（增）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "id": "20e45801",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       fk  wwx  Age   Name\n",
      "day1  NaN  NaN   28    Tom\n",
      "day2  NaN  NaN   34   Jack\n",
      "day3  NaN  NaN   29  Steve\n",
      "day4  NaN  NaN   42  Ricky\n",
      "       fk  jbc  wwx  Age   Name\n",
      "day1  NaN    1  NaN   28    Tom\n",
      "day2  NaN    2  NaN   34   Jack\n",
      "day3  NaN    3  NaN   29  Steve\n",
      "day4  NaN    4  NaN   42  Ricky\n"
     ]
    }
   ],
   "source": [
    "# key作为列标签，value这列的元素\n",
    "data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}\n",
    "\n",
    "# 用index为其添加行标签\n",
    "# 在用columns自定义列标签时，\n",
    "  # 1.如果不包含dict中的某一个key，这个key会被忽略。\n",
    "  # 2.如果dict不存在这个key，会以NaN填充这一列\n",
    "df = pd.DataFrame(data,index=['day1','day2','day3','day4'],columns=['fk','wwx','Age','Name'])\n",
    "\n",
    "print(df)\n",
    "df.insert(1,column='jbc',value=[1,2,3,4])\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d3255fb",
   "metadata": {},
   "source": [
    "### 删除DataFrame列数据（删）\n",
    "#### 列索引删除数据列（删）\n",
    "- 用del方式删除\n",
    "- 用DataFrame.pop()方法删除"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "73bb904f",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      jbc  wwx  Age   Name\n",
      "day1    1  NaN   28    Tom\n",
      "day2    2  NaN   34   Jack\n",
      "day3    3  NaN   29  Steve\n",
      "day4    4  NaN   42  Ricky\n",
      "      jbc  Age   Name\n",
      "day1    1   28    Tom\n",
      "day2    2   34   Jack\n",
      "day3    3   29  Steve\n",
      "day4    4   42  Ricky\n",
      "      Age   Name\n",
      "day1   28    Tom\n",
      "day2   34   Jack\n",
      "day3   29  Steve\n",
      "day4   42  Ricky\n"
     ]
    }
   ],
   "source": [
    "print(df)\n",
    "del df['wwx']\n",
    "print(df)\n",
    "df.pop('jbc')\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "213071ab",
   "metadata": {},
   "source": [
    "## 行索引操作DataFrame\n",
    "### 行索引查找行（查）"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c6b0f7a",
   "metadata": {},
   "source": [
    "#### 标签索引选取（DataFrame.loc方法）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "id": "c0f58f67",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   one  two\n",
      "a  1.0    1\n",
      "b  2.0    2\n",
      "c  3.0    3\n",
      "d  NaN    4\n",
      "one    2.0\n",
      "two    2.0\n",
      "Name: b, dtype: float64\n"
     ]
    }
   ],
   "source": [
    "d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),\n",
    "   'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}\n",
    "df = pd.DataFrame(d)\n",
    "print(df)\n",
    "# df.loc() DataFrame的loc方法\n",
    "# loc只接受标签索引，且只允许接两个参数,第一个是行，第二个是列\n",
    "print(df.loc['b'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "503b107f",
   "metadata": {},
   "source": [
    "#### 整数索引选取（DataFrame.iloc）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 131,
   "id": "c2d967fc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   one  two\n",
      "a  1.0    1\n",
      "b  2.0    2\n",
      "c  3.0    3\n",
      "d  NaN    4\n",
      "3\n",
      "---\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "one    1.0\n",
       "two    1.0\n",
       "Name: a, dtype: float64"
      ]
     },
     "execution_count": 131,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),\n",
    "   'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}\n",
    "df = pd.DataFrame(d)\n",
    "print(df)\n",
    "# iloc只接受整数索引，且只接受两个参数，第一个是行，第二个是列\n",
    "# []接受两个参数，且返回DataFrame\n",
    "print(df.iloc[2,1])\n",
    "print('---')\n",
    "# （）只接受一个，且只有行.返回的是pandas.core.indexing._iLocIndexer,类似迭代器\n",
    "df.iloc(0)[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e07d2fb2",
   "metadata": {},
   "source": [
    "#### 切片操作多行（查）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "id": "d084d30f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   one  two\n",
      "a  1.0    1\n",
      "b  2.0    2\n",
      "c  3.0    3\n",
      "d  NaN    4\n",
      "   one  two\n",
      "c  3.0    3\n",
      "d  NaN    4\n"
     ]
    }
   ],
   "source": [
    "d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),\n",
    "   'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}\n",
    "df = pd.DataFrame(d)\n",
    "#左闭右开\n",
    "print(df)\n",
    "print(df[2:4])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b765a90",
   "metadata": {},
   "source": [
    "### 增加DataFrame的行数据（DataFrame.append）（增）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 126,
   "id": "081f2e77",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     a    b    0    1\n",
      "0  1.0  2.0  NaN  NaN\n",
      "1  3.0  4.0  NaN  NaN\n",
      "0  NaN  NaN  3.0  4.0\n",
      "1  NaN  NaN  5.0  6.0\n",
      "0  5.0  6.0  NaN  NaN\n",
      "1  7.0  8.0  NaN  NaN\n"
     ]
    }
   ],
   "source": [
    "df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])\n",
    "# 在行末追加新数据行,不指定columns会自动按序号生产新列，且在空处用NaN填充\n",
    "df1 = pd.DataFrame([[3, 4], [5, 6]])\n",
    "df = df.append(df1)\n",
    "# 指定现有的columns则会在后面加上\n",
    "df2 = pd.DataFrame([[5, 6], [7, 8]],columns=['a','b'])\n",
    "df = df.append(df2)\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d6d6074",
   "metadata": {},
   "source": [
    "### 删除DataFrame的行数据（DataFrame.drop）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 128,
   "id": "9ae91c17",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   a  b\n",
      "0  1  2\n",
      "1  3  4\n",
      "0  5  6\n",
      "1  7  8\n",
      "   a  b\n",
      "1  3  4\n",
      "1  7  8\n"
     ]
    }
   ],
   "source": [
    "df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])\n",
    "df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])\n",
    "df = df.append(df2)\n",
    "print(df)\n",
    "#注意此处调用了drop()方法\n",
    "df = df.drop(0)\n",
    "print (df)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1913c92e",
   "metadata": {},
   "source": [
    "## DataFrame的常用方法与属性"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff912b56",
   "metadata": {},
   "source": [
    "### 常用方法\n",
    "\n",
    "\n",
    "| 名称    | 方法描述                   |\n",
    "| ------- | -------------------------- |\n",
    "| head()  | 返回前 n 行数据。          |\n",
    "| tail()  | 返回后 n 行数据。          |\n",
    "| shift() | 将行或列移动指定的步幅长度 |\n",
    "\n",
    "1. DataFrame.head()\n",
    "2. DataFrame.tail()\n",
    "- 与Series的一样，不过head与tail都是读前/后n行的\n",
    "3. DataFrame.shift(periods=1, freq=None, axis=0)\n",
    "- 移动 DataFrame 中的某一行/列\n",
    "  + 参数含义：\n",
    "  + periods    //  类型为int，表示移动的幅度，可以是正数，也可以是负数，默认值为1。\n",
    "  + freq      //  日期偏移量，默认值为None，适用于时间序。取值为符合时间规则的字符串。\n",
    "  + axis      //  如果是 0 或者 \"index\" 表示上下移动，如果是 1 或者 \"columns\" 则会左右移动。\n",
    "  + fill_value  //  该参数用来填充缺失值。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "id": "7184cfcf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "原始数据\n",
      "   a_data  b_data  c_data\n",
      "0      40      20      22\n",
      "1      28      37      17\n",
      "2      39      41      11\n",
      "3      32      35      25\n",
      "4      18      45      15\n",
      "整体向下移动3步后\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>a_data</th>\n",
       "      <th>b_data</th>\n",
       "      <th>c_data</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>40.0</td>\n",
       "      <td>20.0</td>\n",
       "      <td>22.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>28.0</td>\n",
       "      <td>37.0</td>\n",
       "      <td>17.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   a_data  b_data  c_data\n",
       "0     NaN     NaN     NaN\n",
       "1     NaN     NaN     NaN\n",
       "2     NaN     NaN     NaN\n",
       "3    40.0    20.0    22.0\n",
       "4    28.0    37.0    17.0"
      ]
     },
     "execution_count": 139,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "info= pd.DataFrame({'a_data': [40, 28, 39, 32, 18], \n",
    "'b_data': [20, 37, 41, 35, 45], \n",
    "'c_data': [22, 17, 11, 25, 15]}) \n",
    "#移动幅度为3\n",
    "print('原始数据')\n",
    "print(info)\n",
    "print('整体向下移动3步后')\n",
    "info.shift(periods=3) "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a33ac03",
   "metadata": {
    "tags": []
   },
   "source": [
    "### DataFrame常用属性\n",
    "|  名称  |                      属性描述                       |\n",
    "| :----: | :------------------------------------------------------: |\n",
    "|   T    |                       行和列转置。                       |\n",
    "|  axes  |       返回一个仅以行轴标签和列轴标签为成员的列表。       |\n",
    "| dtypes |                 返回每列数据的数据类型。                 |\n",
    "| empty  | DataFrame中没有数据或者任意坐标轴的长度为0，则返回True。 |\n",
    "|  ndim  |                轴的数量，也指数组的维数。                |\n",
    "| shape  |          返回一个元组，表示了 DataFrame 维度。           |\n",
    "|  size  |                 DataFrame中的元素数量。                  |\n",
    "| values |        使用 numpy 数组表示 DataFrame 中的元素值。        |\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4768128",
   "metadata": {},
   "source": [
    "# Pandas描述性统计（统计学）\n",
    "## 列举常见的描述统计函数\n",
    "\n",
    "- 在 DataFrame 中，使用聚合类方法时需要指定轴(axis)参数。下面介绍两种传参方式：\n",
    " 1. 对行操作，默认使用 axis=0 或者使用 \"index\"；\n",
    " 2. 对列操作，默认使用 axis=1 或者使用 \"columns\"。\n",
    "\n",
    "- 这些方法是DataFrame对象的方法，也就是说:\n",
    "    - 我们要使用指定列/行的数据时。我们要先选中指定的行列生成新的DataFrame\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "67869706",
   "metadata": {},
   "outputs": [],
   "source": [
    "# # 举例子    \n",
    "#     df = pd.DataFrame(data) # 生成DataFrame\n",
    "#     df1 = df['Name'] # 选中指定行列，生成新的DataFrame\n",
    "#     df1.sum()  或 df['Name'].sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "807f6d0b",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "| 函数名称  |                           描述说明                           |\n",
    "| :-------: | :----------------------------------------------------------: |\n",
    "|  count()  |                    统计某个非空值的数量。                    |\n",
    "|   sum()   |                             求和                             |\n",
    "|  mean()   |                            求均值                            |\n",
    "| median()  |                           求中位数                           |\n",
    "|  mode()   |                            求众数                            |\n",
    "|   std()   |                           求标准差                           |\n",
    "|   min()   |                           求最小值                           |\n",
    "|   max()   |                           求最大值                           |\n",
    "|   abs()   |                           求绝对值                           |\n",
    "|  prod()   |                      求所有数值的乘积。                      |\n",
    "| cumsum()  |     计算累计和，axis=0，按照行累加；axis=1，按照列累加。     |\n",
    "| cumprod() |     计算累计积，axis=0，按照行累积；axis=1，按照列累积。     |\n",
    "|  corr()   | 计算数列或变量之间的相关系数，取值-1到1，值越大表示关联性越强。 |"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "bc41d962",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Name  Age  Rating\n",
      "0    小明   25    4.23\n",
      "1    小明   26    3.24\n",
      "2    小红   25    3.98\n",
      "3    小华   23    2.56\n",
      "4    老赵   30    3.20\n",
      "5    小曹   29    4.60\n",
      "6    小陈   23    3.80\n",
      "7    老李   34    3.78\n",
      "8    老王   40    2.98\n",
      "9    小冯   30    4.80\n",
      "10   小何   51    4.10\n",
      "11   老张   46    3.65\n"
     ]
    }
   ],
   "source": [
    "# 实例\n",
    "## 创建数据\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "d = {'Name':pd.Series(['小明','小明','小红','小华','老赵','小曹','小陈',\n",
    "   '老李','老王','小冯','小何','老张']),\n",
    "   'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),\n",
    "   'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])\n",
    "}\n",
    "df = pd.DataFrame(d)\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6889aa95",
   "metadata": {},
   "source": [
    "### 以DataFrame.sum()求和为例子（其他DataFrame方法一样）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "f3c766a5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Name      小明小亮小红小华老赵小曹小陈老李老王小冯小何老张\n",
      "Age                            382\n",
      "Rating                       44.92\n",
      "dtype: object\n",
      "0     29.23\n",
      "1     29.24\n",
      "2     28.98\n",
      "3     25.56\n",
      "4     33.20\n",
      "5     33.60\n",
      "6     26.80\n",
      "7     37.78\n",
      "8     42.98\n",
      "9     34.80\n",
      "10    55.10\n",
      "11    49.65\n",
      "dtype: float64\n",
      "小明小亮小红小华老赵小曹小陈老李老王小冯小何老张\n"
     ]
    }
   ],
   "source": [
    "# 对整个Frame求和\n",
    "#print(df.sum())\n",
    "#  对整个DataFrame进行列、行求和\n",
    "print(df.sum(axis=0)) # 每一列求和\n",
    "print(df.sum(axis=1)) # 每一行求和\n",
    "#  选择指定的行列，然后\n",
    "df1 = df['Name']\n",
    "print(df1.sum())\n",
    "# print(df['Name'].sum())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19ed9726",
   "metadata": {},
   "source": [
    "### 数据汇总描述DataFrame.describe() \n",
    "describe() 函数显示与 DataFrame 数据列相关的统计信息摘要。示例如下：\n",
    "- ave 平均值\n",
    "- std 标准差\n",
    "- IQR 值(四分位距)\n",
    "- min+max 最值\n",
    "通过 describe() 提供的include能够筛选字符列或者数字列的摘要信息。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "eb45c50e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Name  Age  Rating\n",
      "0    小明   25    4.23\n",
      "1    小明   26    3.24\n",
      "2    小红   25    3.98\n",
      "3    小华   23    2.56\n",
      "4    老赵   30    3.20\n",
      "5    小曹   29    4.60\n",
      "6    小陈   23    3.80\n",
      "7    老李   34    3.78\n",
      "8    老王   40    2.98\n",
      "9    小冯   30    4.80\n",
      "10   小何   51    4.10\n",
      "11   老张   46    3.65\n",
      "       Name        Age     Rating\n",
      "count    12  12.000000  12.000000\n",
      "unique   11        NaN        NaN\n",
      "top      小明        NaN        NaN\n",
      "freq      2        NaN        NaN\n",
      "mean    NaN  31.833333   3.743333\n",
      "std     NaN   9.232682   0.661628\n",
      "min     NaN  23.000000   2.560000\n",
      "25%     NaN  25.000000   3.230000\n",
      "50%     NaN  29.500000   3.790000\n",
      "75%     NaN  35.500000   4.132500\n",
      "max     NaN  51.000000   4.800000\n"
     ]
    }
   ],
   "source": [
    "print(df)\n",
    "# describe 的include参数筛选描述 字段型 还是 数值型\n",
    "# object： 表示对字符列进行统计信息描述； unique：表示有多少种不同的值   top：数据中出现次数最高的值 freq：出现次数最高的那个值（top）的出现频率\n",
    "# number：表示对数字列进行统计信息描述；\n",
    "# all：汇总所有列的统计信息。  \n",
    "print(df.describe(include='all'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "02e5982f",
   "metadata": {},
   "source": [
    "# Pandas自定义函数\n",
    "如果想要应用自定义的函数，或者把其他库中的函数应用到 Pandas 对象中，有以下三种方法：\n",
    "1. 操作整个 DataFrame 的函数：pipe()\n",
    "2. 操作行或者列的函数：apply()\n",
    "3. 操作单一元素的函数：applymap()\n",
    "## 操作整个 DataFrame，DataFrame.pipe(def,value)  \n",
    "- def自定义函数 value参数值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "3030604a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "         c1        c2        c3\n",
      "0 -0.838833  1.438451 -1.864851\n",
      "1  0.557451 -1.762639 -0.194972\n",
      "2 -0.064671  0.088587 -0.232551\n",
      "3 -0.687511 -1.090590 -0.518409\n",
      "         c1        c2        c3\n",
      "0  4.161167  6.438451  3.135149\n",
      "1  5.557451  3.237361  4.805028\n",
      "2  4.935329  5.088587  4.767449\n",
      "3  4.312489  3.909410  4.481591\n"
     ]
    }
   ],
   "source": [
    "#自定义函数\n",
    "def adder(ele1,ele2,ele3):\n",
    "    c = ele1+ele2+ele3\n",
    "    return c\n",
    "#操作DataFrame\n",
    "df = pd.DataFrame(np.random.randn(4,3),columns=['c1','c2','c3'])\n",
    "#相加前\n",
    "print(df)\n",
    "#相加后\n",
    "print(df.pipe(adder,3,2))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c34267b",
   "metadata": {},
   "source": [
    "## 逐行操作或者列的函数：DataFrame.apply(def,value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "eb6b108b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       col1      col2      col3\n",
      "0 -0.996885 -0.125661 -0.517285\n",
      "1  0.632955 -0.714015 -1.357163\n",
      "2 -1.060740  0.457493 -1.298110\n",
      "3  0.563492  0.715435 -1.116603\n",
      "4  0.326605 -0.109558  1.526087\n",
      "-------\n",
      "col1    2.967266\n",
      "col2    1.330652\n",
      "col3    3.012315\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "\n",
    "df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3'])\n",
    "print(df)\n",
    "df.apply(np.mean,axis=0) # 1行 0列\n",
    "print('-------')\n",
    "# 求每一列中最大值与最小值的差（极差）\n",
    "df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3'])\n",
    "print(df.apply(lambda x: x.max() - x.min()))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1337eec",
   "metadata": {},
   "source": [
    "## 对DataFrame的元素逐个操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "f7bed1cb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       col1       col2       col3\n",
      "0 -0.983838   4.598968   9.939157\n",
      "1  6.178330  12.919126  -4.324173\n",
      "2  5.304978  13.602881  -2.293071\n",
      "3  2.926045  14.291848  -2.001232\n",
      "4 -2.392736   7.106086  16.552659\n"
     ]
    }
   ],
   "source": [
    "#自定义函数\n",
    "df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3'])\n",
    "print(df.applymap(lambda x:x*10))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "197178fa",
   "metadata": {},
   "source": [
    "# reindex重置索引\n",
    "## 重置行列标签DataFrame.reindex\n",
    "- 在原来的DataFrame，我们选中我们需要的列+行的标签\n",
    "- 最后，就会返回给我们一个 既满足指定行标签，又满足指定列标签的新DataFrame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "8c4de3b7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "            A     x         y       C           D\n",
      "0  2016-01-01   0.0  0.128534    High   88.852739\n",
      "1  2016-01-02   1.0  0.387546     Low  100.904566\n",
      "2  2016-01-03   2.0  0.735872  Medium  103.392387\n",
      "3  2016-01-04   3.0  0.805496  Medium  115.245247\n",
      "4  2016-01-05   4.0  0.173677     Low   94.459982\n",
      "5  2016-01-06   5.0  0.467993     Low   76.254698\n",
      "6  2016-01-07   6.0  0.492841     Low  103.600838\n",
      "7  2016-01-08   7.0  0.403612  Medium   92.273112\n",
      "8  2016-01-09   8.0  0.283570    High   94.106116\n",
      "9  2016-01-10   9.0  0.043281     Low  100.418839\n",
      "10 2016-01-11  10.0  0.236290  Medium  105.452255\n",
      "11 2016-01-12  11.0  0.115427     Low   99.134099\n",
      "12 2016-01-13  12.0  0.255725    High  107.808854\n",
      "13 2016-01-14  13.0  0.134619    High   97.514314\n",
      "14 2016-01-15  14.0  0.730541    High  105.735250\n",
      "15 2016-01-16  15.0  0.068626    High   82.264651\n",
      "16 2016-01-17  16.0  0.006806  Medium  102.075618\n",
      "17 2016-01-18  17.0  0.223848     Low  108.304084\n",
      "18 2016-01-19  18.0  0.120539    High  106.915695\n",
      "19 2016-01-20  19.0  0.862164    High  100.223046\n",
      "           A       C   B\n",
      "0 2016-01-01    High NaN\n",
      "2 2016-01-03  Medium NaN\n",
      "5 2016-01-06     Low NaN\n",
      "新的DataFrame,同时满足xy标签\n"
     ]
    }
   ],
   "source": [
    "N=20\n",
    "df = pd.DataFrame({\n",
    "   'A': pd.date_range(start='2016-01-01',periods=N,freq='D'),\n",
    "   'x': np.linspace(0,stop=N-1,num=N),\n",
    "   'y': np.random.rand(N),\n",
    "   'C': np.random.choice(['Low','Medium','High'],N).tolist(),\n",
    "   'D': np.random.normal(100, 10, size=(N)).tolist()\n",
    "})\n",
    "print(df)\n",
    "#重置行、列索引标签\n",
    "df_reindexed = df.reindex(index=[0,2,5], columns=['A', 'C', 'B'])\n",
    "print(df_reindexed)\n",
    "print('新的DataFrame,同时满足xy标签')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "8f47dbf8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       col1      col2      col3\n",
      "0  0.069517  1.276257  0.567798\n",
      "1 -0.409452 -0.922722 -0.456109\n",
      "2 -0.471917  0.749919 -1.105699\n",
      "3 -1.574039 -0.080672  1.986361\n",
      "4 -0.354021 -0.608411 -0.742616\n",
      "5  0.599078  0.140400  0.424174\n",
      "6 -0.940620  0.428593 -1.810909\n",
      "7  0.969531  0.655265 -0.493227\n",
      "8  0.614406 -1.519193  1.842651\n",
      "9  0.554991 -0.837001  0.219638\n",
      "       col1      col2      col3\n",
      "0 -0.029804 -0.942188  1.347398\n",
      "1  0.484639 -0.334183 -0.761581\n",
      "2 -0.158211  0.440911  0.290826\n",
      "3 -0.812986 -0.947884  0.318712\n",
      "4 -1.619827 -0.295460  0.665179\n",
      "5 -0.315338  1.808379  0.145356\n",
      "6  1.561876  0.810407  0.092589\n",
      "       col1      col2      col3\n",
      "0  0.069517  1.276257  0.567798\n",
      "1 -0.409452 -0.922722 -0.456109\n",
      "2 -0.471917  0.749919 -1.105699\n",
      "3 -1.574039 -0.080672  1.986361\n",
      "4 -0.354021 -0.608411 -0.742616\n",
      "5  0.599078  0.140400  0.424174\n",
      "6 -0.940620  0.428593 -1.810909\n"
     ]
    }
   ],
   "source": [
    "### a 与 b 的列索引标签必须相同。\n",
    "### 现有 a、b 两个 DataFrame 对象，让a的行索引与 b 相同，您可以使用 reindex_like() 方法。\n",
    "a = pd.DataFrame(np.random.randn(10,3),columns=['col1','col2','col3'])\n",
    "print(a)\n",
    "b = pd.DataFrame(np.random.randn(7,3),columns=['col1','col2','col3'])\n",
    "print(b)\n",
    "a= a.reindex_like(b)\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3eca2cc5",
   "metadata": {},
   "source": [
    "# 填充元素值\n",
    "reindex_like() 提供了一个可选的参数method，使用它来填充相应的元素值，参数值介绍如下：\n",
    "- pad/ffill：向前填充值；\n",
    "- bfill/backfill：向后填充值；\n",
    "- nearest：从距离最近的索引值开始填充。\n",
    "-  limit： 限制填充的最大行数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "f6012a8f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       col1      col2      col3\n",
      "0 -1.592277 -2.230270  2.303038\n",
      "1  0.426636  0.700958  0.009310\n",
      "2       NaN       NaN       NaN\n",
      "3       NaN       NaN       NaN\n",
      "4       NaN       NaN       NaN\n",
      "5       NaN       NaN       NaN\n",
      "       col1      col2      col3\n",
      "0 -1.592277 -2.230270  2.303038\n",
      "1  0.426636  0.700958  0.009310\n",
      "2  0.426636  0.700958  0.009310\n",
      "3  0.426636  0.700958  0.009310\n",
      "4       NaN       NaN       NaN\n",
      "5       NaN       NaN       NaN\n"
     ]
    }
   ],
   "source": [
    "df1 = pd.DataFrame(np.random.randn(6,3),columns=['col1','col2','col3'])\n",
    "df2 = pd.DataFrame(np.random.randn(2,3),columns=['col1','col2','col3'])\n",
    "#使df2和df1行标签相同\n",
    "print(df2.reindex_like(df1))\n",
    "#向前填充\n",
    "print(df2.reindex_like(df1,method='ffill',limit=2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9a949a71",
   "metadata": {},
   "source": [
    "# 重命名标签(DataFrame.rename())\n",
    "rename() 方法允许您使用某些映射(dict或Series)或任意函数来对行、列标签重新命名，示例如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "6ed5b1a0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       col1      col2      col3\n",
      "0 -0.940398 -1.074675 -1.075609\n",
      "1  0.301459 -0.078092 -1.116679\n",
      "2  0.631933  2.294632  0.428294\n",
      "3 -1.581773  0.344891 -1.777163\n",
      "4  1.272871  0.913480 -0.370982\n",
      "5  0.713317  0.744475 -0.981735\n",
      "              c1        c2      col3\n",
      "apple  -0.940398 -1.074675 -1.075609\n",
      "banana  0.301459 -0.078092 -1.116679\n",
      "durian  0.631933  2.294632  0.428294\n",
      "3      -1.581773  0.344891 -1.777163\n",
      "4       1.272871  0.913480 -0.370982\n",
      "5       0.713317  0.744475 -0.981735\n"
     ]
    }
   ],
   "source": [
    "df1 = pd.DataFrame(np.random.randn(6,3),columns=['col1','col2','col3'])\n",
    "print (df1)\n",
    "#对行和列重新命名\n",
    "print (df1.rename(columns={'col1' : 'c1', 'col2' : 'c2'},index = {0 : 'apple', 1 : 'banana', 2 : 'durian'}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea7a6901",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "303.825px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  },
  "toc-autonumbering": true,
  "toc-showcode": false,
  "toc-showmarkdowntxt": true,
  "toc-showtags": true
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
